<?php

class Pictet2_Metahandlers_Xml extends Pictet2_Metahandlers_Abstract {
	
	private $_xml;
	private $_changed = false;
	
	public function __construct() {
		if(!file_exists(".xml")) {
			mkdir(".xml");
			file_put_contents(".xml" . DS . "images.xml", "<images></images>");
		}
		if(!file_exists(".xml/images.xml")) {
			file_put_contents(".xml" . DS . "images.xml", "<images></images>");
		}
		$this->_xml = simplexml_load_file(".xml" . DS . "images.xml");
	}
	
	public function checkMetaModiefied($filename) {
		$found = false;
		$modified = false;
		for($x = 0; $x <= sizeof($this->_xml->image)-1; ++$x) {
			$image = $this->_xml->image[$x];
			if($image->filename == $filename) {
				$found = true;
				if(filemtime($filename) != $image->mtime) {
					$modified = true;
					$this->_xml->image[$x]->mtime = filemtime($filename);
				}
			}
		}
		if(!$found) {
			$add = $this->_xml->addChild('image');
			$add->addChild('filename', $filename);
			$add->addChild('mtime', filemtime($filename));
			
			$modified = true;
		}
		//var_dump($this->_xml->asXml());
		if($modified && !$this->_changed) {
			$this->_changed = true;
		}
		return $modified;		
	}
	
	public function saveMetadata() {
		if($this->_changed) {
			file_put_contents(".xml" . DS . "images.xml", $this->_xml->asXml());
		}
	}
	
}